import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { Setofkey } from "../../../../entity/setofkey.model";
import { SetofkeyService } from "../../../../service/setofkey.service";
import { Observable } from "rxjs/Observable";
import { Command } from "../../../../shared/toolbar.service";
import { Blade } from "../../../../shared/blade/blade.model";
import { BladeData } from "../../../../shared/blade/blade-data";
import { DialogResult } from "../../../../shared/dialog.service";

import { FaultLevel, DeviceCategoryFaultLevel } from "../../../../entity/fault-level.model";
import { FaultLevelEditComponent } from "../fault-level-edit/fault-level-edit.component"
import { FaultLevelService } from "../../../../service/fault_level.service";

import { SoundListComponent } from "../../sound/sound-list/sound-list.component"
import { DeviceCategory } from "../../../../entity/device-category.model";
import { DeviceCategoryService } from "../../../../service/device-category.service";

@Component({
	selector: 'app-fault-level-list',
	templateUrl: './fault-level-list.component.html',
	styleUrls: ['./fault-level-list.component.css']
})
export class FaultLevelListComponent extends BladeContainerBase<FaultLevel> {

	public faultLevelData: FaultLevel[] = [];
	public original: FaultLevel[] = [];
	/**
	 * 设备分类故障等级
	 */
	public DeviceCategoryFaultLevels:DeviceCategoryFaultLevel[] = [];
	/**
	 * 设备分类集合
	 */
	public categoryFileData: DeviceCategory[] = [];

	public active: number = 0;
	
	constructor(
		private faultLevelService: FaultLevelService,
		private deviceCategoryService: DeviceCategoryService,
	) {
		super()
	}

	ngOnInit(): void {
		this.commands = [
			new Command("add", "添加", "fa fa-plus", "setofkey:insert", blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
			new Command("edit", "编辑", "fa fa-edit", "setofkey:update", blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
			new Command("delete", "删除", "fa fa-trash-o", "setofkey:delete", blade => this.exeDelete(blade), blade => this.canDelete(blade))
		];
		super.ngOnInit();
	}

	initData(): any | Observable<any> | Promise<any> {
		// this.faultLevelService.getFaultLevelsWithSound()
		// 	.then(res => {
		// 		if (!res) { return false };
		// 		this.original = [...res];				
		// 		this.faultLevelData = [...this.original];
		// 		console.log(this.faultLevelData)				
		// 	})
		// 	.catch(error => this.bladeData.error = error)
		// 	.then(res => this.bladeData.isLoading = false);



		Promise.all([
			this.faultLevelService.getFaultLevelsWithSound(),
			this.deviceCategoryService.getDeviceCategorys()
		])
		.then(res =>{	
			if(!res[0] && !res[1]){return false}
			this.faultLevelData = [...res[0]];
			this.categoryFileData = [...res[1]];
			this.DeviceCategoryFaultLevels = [];
			this.categoryFileData.forEach(category =>{
				let index = this.DeviceCategoryFaultLevels.findIndex(o =>o.deviceCategoryId == category.deviceCategoryId)
				if(index==-1){
					let faultLevel = this.faultLevelData.filter(o =>o.deviceCategoryId ==category.deviceCategoryId)
					if(faultLevel.length){
						this.DeviceCategoryFaultLevels.push({
						deviceCategoryId:category.deviceCategoryId,
						deviceCategoryName:category.deviceCategoryName,
						faultLevels:[...faultLevel]
					})
				}
					
				}
				
			})
		})
		.catch(error => this.bladeData.error = error)
		.then(res => this.bladeData.isLoading = false);

	}

	exeAdd(blend: Blade): void {
		let data: BladeData = new BladeData();
		data.id = "faultLevelCreate";
		data.title = "新增报警级别";
		data.isClosingDisabled = false;

		let createKeyBlade = this.bladeService.createBlade(FaultLevelEditComponent, data, true, this.currentEntity,this.active);
		this.bladeService.showBlade(createKeyBlade, this.currentBlade);
	}
	canExeAdd(blend: Blade): boolean {
		return true;
	}
	exeEdit(blend: Blade): void {
		if (this.currentEntity != undefined) {

			let data: BladeData = new BladeData();
			data.id = "matrixStateGroupEdit";
			data.title = this.currentEntity.faultLevelName;
			let editFaultLevelBlade = this.bladeService.createBlade(FaultLevelEditComponent, data, false, this.currentEntity);
			this.currentBlade.bladeService.showBlade(editFaultLevelBlade, this.currentBlade);
		}
	}
	canExeEdit(blend?: Blade): boolean {
		return this.currentEntity != null;
	}

	exeDelete(blend: Blade): void {
		let selectedFaultLevel = this.getSelected();
		if (selectedFaultLevel.length > 0) {
			this.dialogService
				.showConfirmationDialog("确认删除", "是否要删除选中项？")
				.subscribe(dialogResult => {
					if (dialogResult == DialogResult.Ok) {
						this.currentBlade.bladeData.isLoading = true;
						this.faultLevelService.batchDelete(selectedFaultLevel.map(o => o.faultLevelId))
							.then(res => {
								if (res) {
									this.refresh(undefined);
								}
							})
							.catch(error => this.bladeData.error = error)
							.then(res => this.bladeData.isLoading = false);
					}
				})

		}

	}
	canDelete(blend?: Blade): boolean {
		return this.getSelected().length > 0;
	}

	onSeletedChange(faultLevel: FaultLevel) {
		if (this.currentBlade.childrenCanDeactivate()) {
			this.showSoundListBlade(faultLevel);
		}
	}

	showSoundListBlade(selected: FaultLevel) {
		if (this.currentEntity != selected
			|| this.bladeService.findBlade("showMatrixStateList") == undefined) {

			let data: BladeData = new BladeData();
			data.id = "showMatrixStateList";
			data.title = "报警声音列表";
			data.isClosingDisabled = false;
			
			let soundListBlade = this.bladeService.createBlade(SoundListComponent, data, false, null, selected);
			this.bladeService.showBlade(soundListBlade, this.currentBlade).then(res => {
				if (res) {
					this.currentEntity = selected;
				}
			});
		}
	}

	/**
	   * 单选
	   * 
	   * @param {any} event 
	   * @param {any} key 
	   * 
	   * @memberof MatrixStateGroupListComponent
	   */
	onItemCheack(event: HTMLInputElement, key: FaultLevel) {
		key.isChecked = event.checked;
	}

	/**
     * 全选/全不选
     * 
     * @param {HTMLInputElement} event 
     * 
     * @memberof MatrixStateGroupListComponent
     */
	onAllCheack(event: HTMLInputElement) {
		
		if (this.DeviceCategoryFaultLevels[this.active].faultLevels.length > 0) {
			for (let i = 0; i < this.DeviceCategoryFaultLevels[this.active].faultLevels.length; i++) {
				this.DeviceCategoryFaultLevels[this.active].faultLevels[i].isChecked = event.checked;
			}
		}
		
		// if (this.faultLevelData.length > 0) {
		// 	for (let i = 0; i < this.faultLevelData.length; i++) {
		// 		this.faultLevelData[i].isChecked = event.checked;
		// 	}
		// }
		console.log(this.DeviceCategoryFaultLevels[this.active].faultLevels)
	}
    /**
    * 获得选中项
    * 
    * @returns {Setofkey[]} 
    * 
    * @memberof MatrixStateGroupListComponent
    */
	getSelected(): FaultLevel[] {
		
		
		if (this.faultLevelData.length > 0) {
			let filter = this.faultLevelData.filter(ref => ref.isChecked==true)
			return filter == null ? [] : filter;
		}
		return [];
	}

	onClickTitle(n:number){
		this.active = n;
	}

}



// WEBPACK FOOTER //
// ./src/app/module/basic/fault-level-config/fault-level-list/fault-level-list.component.ts